<!-- 维修审批 -->
<template>
  <div class="app-container">
    <!-- 表格状态切换按钮 -->
    <ul class="nav">
      <li v-for="v in navData" :class="{ active: v.value == queryParams.approvealStatus }"
        @click="navChangeHandle(v.value)">
        {{ v.label }}
      </li>
    </ul>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <searchType v-for="v in searchProps" :data="v" :selects="sel_option[v.prop]" v-model="queryParams[v.prop]"
        :handleQuery="handleQuery">
      </searchType>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['gwc:repair:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['gwc:repair:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['gwc:repair:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['gwc:repair:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column :label="v.label" align="center" :prop="v.prop" :width="v.width" v-for="v in tableProps"
        show-overflow-tooltip>
        <template #default="scope">
          <dict-tag v-if="v.prop == 'repairReason'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="applyDetail(scope.row)" v-show="queryParams.approvealStatus == '0'"
            v-hasPermi="['gwc:application:edit']">审批详情</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-show="queryParams.approvealStatus != '0'"
            v-hasPermi="['gwc:application:edit']">审批</el-button>
          <!-- <el-button link type="primary" @click="handleUpdate(scope.row, true)" v-show="queryParams.approvealStatus != '0'"
            v-hasPermi="['gwc:application:edit']">通过</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row, false)" v-show="queryParams.approvealStatus != '0'"
            v-hasPermi="['gwc:application:remove']">不通过</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 审批对话框 -->
    <el-dialog :title="title" v-model="handleOpen" width="800px" class="sky-form">
      <el-form ref="repairRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item v-for="v in successEditParams" :key="v.prop" :label="v.label" :prop="v.prop" :class="v.type">
          <template v-if="v.prop == 'repairCompany'">
            <el-input v-model="form[v.prop]" type="textarea" :rows="1" style="width: calc(100% - 24px);"
              :disabled="true" />
          </template>
          <el-input v-else-if="v.type == 'input'" v-model.trim="form[v.prop]" :disabled="true"></el-input>
          <el-select v-else-if="v.type == 'select'" v-model="form[v.prop]" filterable clearable :disabled="true">
            <el-option v-for="item in sel_option[v.prop]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-tree-select v-else-if="v.type == 'treeSelect'" v-model="form[v.prop]" clearable :data="sel_option[v.prop]"
            :expand-on-click-node="false" :render-after-expand="false" check-strictly :props="{ label: 'label' }"
            node-key="id" filterable placeholder="" :disabled="true" />
          <ImageUpload :limit="6" :rank="0" ref="fileUpload" url='/gwc/repairManagement/uploadRepair'
            :pictures='form[v.prop] || []' v-else-if="v.type == 'photo'" :disabled="true">
          </ImageUpload>
          <el-date-picker v-else-if="v.type == 'datePicker'" v-model="form[v.prop]" type="datetime"
            :disabled-date="disabledDate" value-format="YYYY-MM-DD HH:mm:ss" :disabled="true"/>
          <el-select v-model="form[v.prop]" filterable remote reserve-keyword placeholder="请输入光伏板编号查询"
            v-else-if="v.type == 'carSelect'" :disabled="true">
            <el-option v-for="item in sel_option[v.prop]" :key="item.id" :label="item.numberPlate" :value="item.id" />
          </el-select>
          <el-select v-model="form[v.prop]" filterable remote reserve-keyword placeholder="请输入负责人查询"
            v-else-if="v.type == 'driverSelect'" :disabled="true">
            <el-option v-for="item in sel_option[v.prop]" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-input v-else-if="v.type == 'textarea'" v-model="form[v.prop]" type="textarea" :rows="1"
            :disabled="true" />
        </el-form-item>
        <el-form-item label="审批意见" prop="remarks" class="textarea">
          <el-input v-model="form.remarks" placeholder="请输入审批意见" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(true)">通 过</el-button>
          <el-button @click="submitForm(false)">不 通 过</el-button>
          <el-button type="danger" @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情申请用车审批对话框 -->
    <el-dialog title="审批详情" v-model="open" width="800px" append-to-body :destroy-on-close="true" class="sky-form">
      <el-table :data="applyDetailData" style="height: 600px;">
        <el-table-column label="序号" align="center" type="index" :width="55"> </el-table-column>
        <el-table-column :label="v.label" align="center" :prop="v.prop" :width="v.width" v-for="v in detailTableProps">
          <template #default="scope">
            <dict-tag v-if="v.prop == 'approvealStatus'" :options="sel_option.applicationTableOrderStatus"
              :value="scope.row[v.prop]" />
            <dict-tag v-else-if="v.prop == 'purpose'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
            <span v-else>{{ scope.row[v.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Repair" lang="ts">
import { getApprovalRepairList, getManagement, delManagement, addManagement, updateManagement } from "@/api/gwc/repairManagement";
import { delRepair, addRepair, getApprovalRepairId, updateRepair } from "@/api/gwc/repair";
import { searchComponentType } from "@/components/tableRelate/searchTypeTs"
import { getSearchCompanyListRole } from "@/api/system/dept";
import useUserStore from '@/store/modules/user'
import searchType from "@/components/tableRelate/searchType.vue";
import dayjs from "dayjs"
const { proxy } = getCurrentInstance() as any;

const repairList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const handleOpen = ref(false);
const applyDetailData = ref([]);
const data: any = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    approvealStatus: '2',
  },
  rules: {
    repairId: [
      { required: true, message: "维修单id不能为空", trigger: "blur" }
    ],
  }
});
const sel_option = ref<any>({});
const treeList = ref([]);
const user = useUserStore().info as { userName: string, phonenumber: string, dept: { id: string, deptName: string } };
getSearchCompanyListRole().then(res => {
  treeList.value = res.data
  sel_option.value.companyId = res.data
});
const { queryParams, form, rules } = toRefs(data);

// 审批状态（0:通过，1：不通过，2：待审批）
const navData = reactive([
  { label: "待审批", value: "2" },
  { label: "已审批", value: "0" },
])
const detailTableProps = reactive([
  { label: "所属部门", prop: "companyName" },
  { label: "审批时间", prop: "createTime", width: "180" },
  { label: "审批意见", prop: "remarks", width: "360" },
])
const searchProps = reactive([
  { label: "光伏板编号", prop: "1", type: searchComponentType.input },
  { label: "所属部门", prop: "companyId", type: searchComponentType.treeSelect },
  { label: "委托维修单位", prop: "2", type: searchComponentType.input },
  { label: "送修人", prop: "3", type: searchComponentType.input },
])
const tableProps = reactive([
  { label: "所属部门", prop: "companyName", width: "120" },
  { label: "负责人姓名", prop: "driverName", width: "120", },
  { label: "光伏板编号", prop: "numberPlate", width: "120" },
  { label: "申请人电话", prop: "contactNumber", width: "120" },
  { label: "委托维修单位", prop: "repairCompany", width: "120" },
  { label: "预约维修项目", prop: "orderRepair", width: "120", type: "dict" },
  { label: "维修原因", prop: "repairReason", width: "120", type: "dict" },
  { label: "维修费用(元)", prop: "repairCostStr", width: "120" },
  { label: "送修里程(km)", prop: "repairRepairStr", width: "120" },
  { label: "预计费用(元)", prop: "expectCostStr", width: "120" },
  { label: "送修时间", prop: "repairTime", width: "180" },
  { label: "厂牌型号", prop: "brandModel", width: "120" },
  { label: "备注说明", prop: "remark", width: "120" },
])
const successEditParams = reactive([
  { label: "所属部门", prop: "companyId", type: "treeSelect" },
  { label: "光伏板编号", prop: "vehicleId", type: "carSelect" },
  { label: "负责人姓名", prop: "driverId", type: "driverSelect", },
  { label: "送修里程(km)", prop: "repairRepairStr", type: "input" },
  { label: "送修时间", prop: "repairTime", type: "datePicker" },
  { label: "厂牌型号", prop: "brandModel", type: "input" },
  { label: "委托维修单位", prop: "repairCompany", type: "textarea", required: true },
  { label: "预约维修项目", prop: "orderRepair", type: "textarea" },
  { label: "维修原因", prop: "repairReason", type: "select" },
  { label: "预计费用(元)", prop: "expectCostStr", type: "input" },
  { label: "备注说明", prop: "remark", type: "textarea" },
  { label: "申请凭证", prop: "imageList", type: "photo" },
  { label: "维修费用(元)", prop: "repairCostStr", type: "input" },
  { label: "维修凭证", prop: "imageRepair", type: "photo" },
])
const disabledDate = (time: Date) => {
  const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
  const today = new Date();
  const yesterday = new Date(today.getTime() - oneDay);
  return time.getTime() <= yesterday.getTime()
}
let dictList = tableProps.filter(v => v.type == 'dict').map(v => v.prop);
sel_option.value = proxy.useDict.apply(this, [...dictList, "repairTableOrderStatus"]);

function navChangeHandle(val) {
  queryParams.value.approvealStatus = val;
  handleQuery();
}

/** 查询申请维修审批列表 */
function getList() {
  loading.value = true;
  getApprovalRepairList(queryParams.value).then((response: any) => {
    repairList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 审批详情
function applyDetail(row) {
  const _repairId = row.repairId;
  getApprovalRepairId(_repairId).then(response => {
    applyDetailData.value = response.data;
    open.value = true;
  })
}


// 取消按钮
function cancel() {
  open.value = false;
  handleOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
  };
  proxy.resetForm("repairRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.repairId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加申请维修审批";
}

/** 修改按钮操作 */
function handleUpdate(row, bool: Boolean | null) {
  reset();
  const _approvalId = row.repairId || ids.value
  getManagement(_approvalId).then(response => {
    form.value = response.data;
    handleOpen.value = true;
    title.value = "维修审批";
  });
}

/** 提交按钮 */
function submitForm(bool) {
  proxy.$refs["repairRef"].validate(valid => {
    if (valid) {
      if (bool == true) {
        form.value.approvealStatus = 0;
      } else if (bool == false) {
        form.value.approvealStatus = 1;
      }
      addRepair({
        repairId: form.value.repairId,
        remarks: form.value.remarks,
        approvealStatus: form.value.approvealStatus,
      }).then(response => {
        proxy.$modal.msgSuccess("审批成功");
        cancel();
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _approvalIds = row.repairId || ids.value;
  proxy.$modal.confirm('是否确认删除申请维修审批编号为"' + _approvalIds + '"的数据项？').then(function () {
    return delRepair(_approvalIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('gwc/repair/export', {
    ...queryParams.value
  }, `维修审批_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}

getList();
</script>
<style scoped lang="scss">
.textarea,
.destination,
.photo {
  display: block-flex !important;
  display: flex !important;
  width: calc(100% - 64px)
}

.disableClass {
  :deep(.item-actions) {
    opacity: 0 !important;
  }
}

:deep(.apply-window) {
  margin-top: 30vh;
}
</style>